package com.mtask.common.utils;


import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.util.Strings;

import java.io.IOException;

public class WebUtil {
    private WebUtil() {
    }

    public static boolean visit(String url, boolean... force200) {
        boolean visited = true;
        try {
            HttpResponse response = visitWithResult(url);
            if (force200 != null && response.getStatusLine().getStatusCode() != 200) {
                visited = false;
            }
        } catch (IOException ioException) {
            visited = false;
        }
        return visited;
    }

    public static HttpResponse visitWithResult(String url) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        return httpClient.execute(get);
    }

    public static String visitWithResultString(String url) {
        String result;
        try {
            HttpResponse response = visitWithResult(url);
            result = EntityUtils.toString(response.getEntity());
        } catch (IOException ioException) {
            result = Strings.EMPTY;
        }
        return result;
    }
}
